import { createRouter, createWebHistory } from 'vue-router'
import Layout from '@/layout/index.vue'
import { getAuthRouters } from "@/router/authRouter";
import { getDynamicRoutes } from '@/utils/getRouteList.js'
import { useAuthRouterStore } from '@/stores/authRouter.js'
import useTagStore from '@/stores/tagList'
import useUserStore from "@/stores/user.js";
import { isRelogin } from '@/utils/request'
import { getToken, removeToken } from '@/utils/auth'

import { ElNotification } from 'element-plus'


const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: '首页',
      component: Layout,
      redirect: '/home',
      meta: {
        staticRouter: true // 静态路由
      },
      children: [{
        path: 'home',
        name: 'home',
        component: () => import('@/views/home/index.vue'),
        meta: {
          breadcrumbName: '首页',
          icon: 'home',
          keepAlive: true,
          staticRouter: true // 静态路由
        }
      }]
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('@/views/Login/index.vue'),
    },
    // {
    //   path: "/redirect",
    //   name: 'redirect',
    //   component: () => import('@/views/home/redirect.vue'),
    // }
  ],
})


// 验证token
router.beforeEach((to, from, next) => {
  // console.log(getToken(), 'getToken');
  if (!getToken()) {
    if (to.path !== '/login') {
      ElNotification({
        title: '重新登录',
        message: '您的登录已过期，正在为您跳转到登录页面...',
        duration: 2000,
      })
      return new Promise((resolve) => {
        setTimeout(() => {
          next('/login');
        }, 2000);
      });
    } else {
      next();
    }
  } else {
    // token 存在并且 去往非登录页 前路由非/
    // 需校验token是否有效
    if (useUserStore().roles.length === 0) {
      isRelogin.show = true
      // 判断当前用户是否已拉取完user_info信息
      useUserStore().getInfo().then(async(res) => {
        isRelogin.show = false
        const authRouterStore = useAuthRouterStore()
        let { routerList } = authRouterStore
        if (!routerList.length) {
          // 动态添加路由
          let dynamicRoutes =await getDynamicRoutes()
          let newRoutes = getAuthRouters(dynamicRoutes)

          authRouterStore.addRouterList(newRoutes)
          newRoutes.forEach(val => {
            router.addRoute(val)
          })
          next({...to,replace: true})
        } else {
          next()
        }
      }).catch(err => {
        
        removeToken()
        console.log(err, '23131', getToken());
        ElNotification({
          title: '重新登录',
          message: '您的登录已过期，正在为您跳转到登录页面...',
          duration: 2000,
        })
        return new Promise((resolve) => {
          setTimeout(() => {
            next('/login');
          }, 2000);
        });
      })
    } else {
      next()
    }
  }
})
export default router
